I know there's like 8 line solutions to convert integers to binary, but I'm trying my hand at creating a little program that does the same thing with arrays. I'm using 3 arrays, the first stores the original number to be converted and all the values of dividing that number by 2 and then rounding down when there's a remainder, aka [122, 61, 61, 30.5, 30, 15.5, 15, etc. etc.], and the second array will store the binary digits based on if remainder of division is true || false, aka [0,1,0,1,1,1,1]. Not yet written, but at the end I'll take the binaryArray and reverse and toString it to get 1111010, the correct binary for 211.
Obviously I'm doing more than one thing wrong, but I'm getting close as I can see the correct initial results when I console.log the main function. Any help here is appreciated, except I don't need to know how to do this entire concept easier, as I've already studied the easier solutions and am attempting this on purpose for practice.
Run the code snippet to see that the output is close to the solution, but obviously lastNumArray is not being updated and the entire thing is not looping.
let num = 122;
let array = [num];
let binaryArray = [];
let lastNumArray = array[array.length - 1];
function convertToBinary(number) {
let lastNumArray = number;
var result = (number - Math.floor(number)) !== 0;
if (result) {
binaryArray.push('1') &&
array.push(lastNumArray / 2) &&
array.push(Math.floor(array[array.length - 1]))
} else {
binaryArray.push('0') &&
array.push(lastNumArray / 2) && //this pushes 61
array.push(Math.floor(array[array.length - 1]))
}
}
while (array > 1) {
convertToBinary(lastNumArray) &&
lastNumArray.push(array[array.length - 1])
}
console.log(array)
console.log(binaryArray)
console.log(lastNumArray)
Any help or pointers here would be much appreciated. I've tried for loops, do while loops, and more and I'm getting close, but I really want to find out what I'm doing wrong here so I can learn. This is the first little function I've tried to write solo, and it's definitely keeping me humble!
You could try something like that with recursive call
let results = []
let binary = []
function cb(number) {
if (number === 0) return
results.push(number)
results.push(number / 2)
results.push(Math.floor(number / 2))
const last_index = results.length - 1
if (results[last_index] === results[last_index - 1]) {
binary.push("0")
} else {
binary.push("1")
}
cb(results[last_index])
}
cb(122)
console.log(results)
console.log(binary)
console.log(binary.reverse().join(""))